package cn.mason.echarts.dao.impl;


import cn.mason.echarts.dao.UserDao;
import cn.mason.echarts.model.User;
import com.mongodb.client.result.UpdateResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service("UserDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public int deleteByPrimaryKey(String id) {
        User user=new User();
        user.setId(id);
        mongoTemplate.remove(user,"user");
        return 0;
    }

    @Override
    public int insert(User record) {
        mongoTemplate.insert(record,"user");
        return 1;
    }

    @Override
    public User selectByPrimaryKey(String id) {
        Criteria c=new Criteria();
        c.and("_id").is(new ObjectId(id));
        User User=mongoTemplate.findOne(Query.query(c),User.class,"user");
        return User;
    }


    @Override
    public  List<User> listAll(){
        return mongoTemplate.findAll(User.class,"user");
    }

    @Override
    public List<User> listPage(int fromIndex,int toIndex) {
        return mongoTemplate.findAll(User.class,"user").subList(fromIndex,toIndex);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        Query query=new Query();
        query.addCriteria(Criteria.where("id").is(record.getId()));
        Update update=new Update();

        UpdateResult updateResult=mongoTemplate.updateFirst(query,update,User.class,"user");
        return 1;
    }

    @Override
    public List<User> listByParams(Map<String,Object> params){
        Iterator entries = params.entrySet().iterator();
        Query query=new Query();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key =(String) entry.getKey();
            Object value = entry.getValue();
            query.addCriteria(Criteria.where(key).is(value));
        }
        return mongoTemplate.find(query,User.class,"user");
    }

    @Override
    public User findByAccount(String account) {
        Criteria c=new Criteria();
        c.and("account").is(account);
        User user = mongoTemplate.findOne(Query.query(c),User.class,"user");
        return user;
    }
}
